package com.kevin.jvm;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author kevin lau
 */
public class MyClassLoader extends ClassLoader {

    private String classPath;

    public MyClassLoader(String classPath) {
        this.classPath = classPath;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if (name.contains("java.")) {
            return super.loadClass(name);
        }
        byte[] data;
        try {
            data = loadByte(name);
        } catch (IOException e) {
            e.printStackTrace();
           return super.loadClass(name);
        }
        return defineClass(name, data, 0, data.length);
    }

    private byte[] loadByte(String name) throws IOException {
        name = name.replaceAll("\\.", "/");
        String dir = classPath + "/" +  name + ".class";
        FileInputStream fis = new FileInputStream(dir);
        int len = fis.available();
        byte[] result = new byte[len];
        fis.read(result);
        fis.close();
        return result;
    }
}
